package se.study.io.oth;

import java.io.*;

/**
 * @Author: tiger
 * @Date:2018/5/8
 * @Description:其他流：内存流、合并流（顺序流）
 */
public class OtherStudy {
    public static void main(String[] args) {
        try {
            byteArrayOutputStream();
            charArrayWriter();
            stringWriter();
            sequenceInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sequenceInputStream() throws IOException {
        //定义字节输入合并流
        SequenceInputStream seinput = new SequenceInputStream(
                new FileInputStream("io/a.txt"), new FileInputStream("io/b.txt"));
        byte[] buffer = new byte[10];
        int len = -1;
        while ((len = seinput.read(buffer)) != -1) {
            System.out.println(new String(buffer, 0, len));
        }

        seinput.close();
    }

    private static void stringWriter() throws IOException {
        //字符串输出流,底层采用 StringBuffer 进行拼接
        StringWriter sw = new StringWriter();
        sw.write("ABCD");
        sw.write("帅锅");
        System.out.println(sw.toString());//ABCD帅锅
        //字符串输入流
        StringReader sr = new StringReader(sw.toString());
        char[] buffer = new char[10];
        int len = -1;
        while ((len = sr.read(buffer)) != -1) {
            System.out.println(new String(buffer, 0, len));//ABCD帅锅
        }
    }

    private static void charArrayWriter() throws IOException {
        //字符数组输出流
        CharArrayWriter caw = new CharArrayWriter();
        caw.write("ABCD");
        //返回内存数据的副本
        char[] temp = caw.toCharArray();
        System.out.println(new String(temp));

        //字符数组输入流
        CharArrayReader car = new CharArrayReader(temp);
        char[] buffer = new char[10];
        int len = -1;
        while ((len = car.read(buffer)) != -1) {
            System.out.println(new String(buffer, 0, len));
        }
    }

    private static void byteArrayOutputStream() throws IOException {
        //字节数组输出流：程序---》内存
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //将数据写入到内存中
        bos.write("ABCD".getBytes());
        //创建一个新分配的字节数组。 其大小是此输出流的当前大小，缓冲区的有效内容已被复制到其中。
        byte[] temp = bos.toByteArray();
        System.out.println(new String(temp, 0, temp.length));

        byte[] buffer = new byte[10];
        ///字节数组输入流：内存---》程序
        ByteArrayInputStream bis = new ByteArrayInputStream(temp);
        int len = -1;
        while ((len = bis.read(buffer)) != -1) {
            System.out.println(new String(buffer, 0, len));
        }

        //这里不写也没事，因为源码中的 close()是一个空的方法体
        bos.close();
        bis.close();
    }
}
